<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of ArvatoApiService
 *
 * @author dxx
 */

namespace app\common\service;

use app\common\model\log\arvatoApiPushLogs as arvatoApiPushLogsModel;

class ArvatoApiService {

    use \app\common\traits\ApiPost;

    public function send($fuc, $params) {

        $arvatoApiPushLogsModel = new arvatoApiPushLogsModel();

        $url = config('arvatoURL');
        $params = json_encode($params);

        $url .= $fuc;

        //私钥
        $prKey = openssl_pkey_get_private($this->_create_private_key(config('arvatoPrivateKey')));

        //公钥
        $puKey = openssl_pkey_get_public($this->_create_public_key(config('arvatoPublicKey')));

        //    openssl_private_encrypt($params, $crypted, $prKey); //加密
        //openssl_public_encrypt($params, $crypted, $puKey); //加密，arvato使用公钥加密
        //分段加密
        foreach (str_split($params, 117) as $chunk) {
            openssl_public_encrypt($chunk, $encryptData, $puKey); //加密，arvato使用公钥加密
            $crypted .= $encryptData;
        }

        $crypted = base64_encode($crypted);

//      openssl_public_decrypt($crypted, $decrypted,$puKey);//解密
        //加入重试机制
        $tryTimes = 2;
        do {
            $tryTimes--;

            try {
                $res = $this->_postArr($url, $crypted, 'json', 4);
                break;
            } catch (\Exception $e) {
                $arvatoApiPushLogsModel->addLog($params, ['msg' => $e->getMessage()], $url, ['msg' => $e->getMessage()], $tryTimes);

                //为了确保数据稳定<=
                if ($tryTimes <= 1) {
                    
                    $mailStr = '调用arvato接口失败,'."\n";
                    $mailStr .= '调用接口：'.$url."\n";
                    $mailStr .= '调用时间：'.date('Y-m-d H:i:s',time())."\n";
                    $mailStr .= '入参：'.$params."\n";
                    $mailStr .= '失败原因：'.$e->getMessage()."\n";
                    $mailStr .= '8秒钟连续调用2次无响应。';
                    
                    try {
                        MailService::sendMail('arvato接口调用报警', $mailStr,config('arvatoAlarmEmail'));
                    } catch (\Exception $ex) {
                        
                    }
                    
                    return $this->outPutError(['msg' => $e->getMessage()]);
                }
            }
        } while ($tryTimes);

        $res = json_decode($res, true);

        if ($res['StatusCode'] == 'S01') {

//            if ($res['ErrorMessage'] == '保存成功') {
//                $decrypted = ['status' => 'success'];
//            } else {

            $result = $res['Data'];

            $result = base64_decode($result);

            //openssl_private_decrypt($result, $decrypted, $prKey); //解密
            //分段解密
            foreach (str_split($result, 128) as $chunk) {
                openssl_private_decrypt($chunk, $decryptData, $prKey); //私钥解密
                $decrypted .= $decryptData;
            }

            $decrypted = base64_decode($decrypted);

            $decrypted = json_decode($decrypted, true);

            if ($decrypted === null) {
                $decrypted = ['status' => 'success'];
            }
            // }
        } else {

            $arvatoApiPushLogsModel->addLog($params, $res, $url, $res);

            return $res;
        }

        $arvatoApiPushLogsModel->addLog($params, $decrypted, $url, $res);

        return $decrypted;
    }

    private function _create_private_key($priKey) {
        $res = "-----BEGIN RSA PRIVATE KEY-----\n" .
                wordwrap($priKey, 64, "\n", true) .
                "\n-----END RSA PRIVATE KEY-----";
        return $res;
    }

    private function _create_public_key($priKey) {
        $res = "-----BEGIN PUBLIC KEY-----\n" .
                wordwrap($priKey, 64, "\n", true) .
                "\n-----END PUBLIC KEY-----";
        return $res;
    }

}
